﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Cinemacenter.Shared
{
	public class WebService
	{
		public static readonly WebService Shared = new WebService ();
		public const string RequestBaseURI = "http://www.ldbarberon.com.ar/marquecine/";

		Marquee _movies;
		UpcomingMovies _upcoming;
		CityCollection _cities;

		public async Task<CityCollection> GetCities ()
		{
			_cities = await Task.Factory.StartNew (() => {
				try {
					var request = CreateRequest ("data/cities.json");
					string response = ReadResponseText (request);
					var json = Newtonsoft.Json.JsonConvert.DeserializeObject < CityCollection > (response);
					return json;
				} catch (Exception ex) {
					Console.WriteLine (ex);
					return new CityCollection ();
				}
			});
			return _cities;
		}

		public async Task<Marquee> GetMovies (int cityId)
		{
			_movies = await Task.Factory.StartNew (() => {
				try {
					var request = CreateRequest (String.Format ("data/{0}/movies.json", cityId));
					string response = ReadResponseText (request);
					var res = Newtonsoft.Json.JsonConvert.DeserializeObject < Marquee > (response);
					return res;
				} catch (Exception ex) {
					Console.WriteLine (ex);
					Console.WriteLine ("URL: " + RequestBaseURI + String.Format ("data/{0}/movies.json", cityId));
					return new Marquee ();
				}
			});
			return _movies;
		}

		public async Task<UpcomingMovies> GetUpcoming (int cityId)
		{
			_upcoming = await Task.Factory.StartNew (() => {
				try {
					var request = CreateRequest (String.Format ("data/{0}/upcoming.json", cityId));
					string response = ReadResponseText (request);
					return Newtonsoft.Json.JsonConvert.DeserializeObject < UpcomingMovies > (response);
				} catch (Exception ex) {
					Console.WriteLine (ex);
					Console.WriteLine ("URL: " + RequestBaseURI + String.Format ("data/{0}/upcoming.json", cityId));
					return new UpcomingMovies ();
				}
			});
			return _upcoming;
		}

		static HttpWebRequest CreateRequest (string location)
		{
			var request = (HttpWebRequest)WebRequest.Create (RequestBaseURI + location + string.Format ("?tsvt={0}", new DateTime ().CurrentTimeMillis ()));
			request.Method = "GET";
			request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
			request.Timeout = 30000;
			return request;
		}

		protected static string ReadResponseText (HttpWebRequest req)
		{
			using (WebResponse resp = req.GetResponse ()) {
				using (Stream s = (resp).GetResponseStream ()) {
					using (var r = new StreamReader (s, Encoding.UTF8)) {
						return r.ReadToEnd ();
					}
				}
			}
		}
	}
}
